package com.victor.controller.mobile;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.victor.entity.Bookcase;
import com.victor.entity.PictureStatic;
import com.victor.entity.Seriesandpicbook;
import com.victor.service.BookcaseService;
import com.victor.service.PictureStaticService;
import com.victor.service.SeriesandpicbookService;
import com.victor.service.YhUsersService;
import com.victor.utils.Msg;

/**
 * 书架 controller
 * 
 * @author Administrator
 *
 */
@RestController
@RequestMapping("/picture/bookcase")
public class BookcaseController {

	@Autowired
	private BookcaseService service;

	@Autowired
	private PictureStaticService staticService;

	@Autowired
	private SeriesandpicbookService spService;

	@Autowired
	private YhUsersService yhService;

	@Autowired
	private PlatformTransactionManager txManager;

	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	/**
	 * 首页 -我的书架
	 * 
	 * @param userid
	 * @return
	 */
	@GetMapping("/getBookcase/{pictype}/{userid}")
	public Msg getBookcase(@PathVariable("userid") String userid, @PathVariable("pictype") Integer pictype) {
//		service.updateOverdue();
		List<Map<String, String>> list = service.findByUseridm(userid, 3, null, pictype);
		return Msg.success().add("bookcase", list);
	}

	/**
	 * 首页 -我的书架 -更多
	 * 
	 * @param userid
	 * @return
	 */
	@GetMapping("/getBookcase/{pictype}/{userid}/more")
	public Msg getBookcaseMore(@PathVariable("userid") String userid, @PathVariable("pictype") String pictype) {
//		service.updateOverdue();
		Bookcase b = new Bookcase();
		b.setBUserId(userid);
		b.setBPicType(pictype);
		List<Map<String, String>> list = service.findByAttribute(b);
		List<Map<String, String>> collect = list.stream().filter(a -> a.get("btype").equals("1")).limit(7L)
				.collect(Collectors.toList());
		List<Map<String, String>> subscribe = list.stream().filter(a -> a.get("btype").equals("2")).limit(7L)
				.collect(Collectors.toList());

		return Msg.success().add("collect", collect).add("subscribe", subscribe);
	}

	/**
	 * 我的收藏
	 * 
	 * @param userid
	 * @param pictype
	 * @return
	 */
	@GetMapping("/getCollect/{pictype}/{userid}")
	public Msg getCollect(@PathVariable("userid") String userid, @PathVariable("pictype") String pictype) {
		Bookcase b = new Bookcase();
		b.setBPicType(pictype);
		b.setBType("1");
		b.setBUserId(userid);
		List<Map<String, String>> list = service.findByAttribute(b);
		return Msg.success().add("collect", list);
	}

	/**
	 * 我的订购
	 * 
	 * @param userid
	 * @param pictype
	 * @return
	 */
	@GetMapping("getSubscribe/{pictype}/{userid}")
	public Msg getSubscribe(@PathVariable("userid") String userid, @PathVariable("pictype") String pictype) {
		Bookcase b = new Bookcase();
		b.setBPicType(pictype);
		b.setBType("2");
		b.setBUserId(userid);
		List<Map<String, String>> list = service.findByAttribute(b);

		return Msg.success().add("subscribe", list);
	}

	/**
	 * 新增 书架信息
	 * 
	 * @param bookcase
	 * @return
	 */
	@Deprecated
	@PostMapping("/insert")
	public Msg insert(Bookcase bookcase) {
		// TODO 订购时 支付等操作
		boolean bool = service.insert(bookcase);
		if (!bool) {
			return Msg.fail("新增书架信息失败");
		}
		// 新增绘本状态
		PictureStatic p = new PictureStatic();
		p.setSUserId(bookcase.getBUserId());
		p.setSPicId(bookcase.getBPicId());
		if (bookcase.getBType().equals("1")) {
			p.setSIsSC("1");
		} else if (bookcase.getBType().equals("2")) {
			p.setSIsJS("1");
		}
		bool = staticService.insert(p);
		if (!bool) {
			return Msg.fail("新增绘本状态失败");
		}
		return Msg.success();
	}

	/**
	 * 收藏 绘本
	 * 
	 * @param bookcase
	 * @return
	 */
	@PostMapping("/addCollect")
	public Msg addCollect(Bookcase bookcase) {
		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
		def.setPropagationBehavior(DefaultTransactionDefinition.PROPAGATION_REQUIRED);
		TransactionStatus status = txManager.getTransaction(def);

		try {
			bookcase.setBType("1"); // 设置类型为 收藏
			bookcase.setBTime(sdf.format(new Date()));
			boolean bool = service.insert(bookcase);
			if (!bool) {
				txManager.rollback(status);
				return Msg.fail("收藏绘本失败");
			}
			// bool = yhService.addExp(bookcase.getBUserId(), 15);
			// if(!bool) {
			// txManager.rollback(status);
			// return Msg.fail("增加经验失败");
			// }
		} catch (Exception e) {
			txManager.rollback(status);
			e.printStackTrace();
			return Msg.fail(e.getMessage());
		}
		txManager.commit(status);
		return Msg.success();
	}

	/**
	 * 订阅免费或 限时免费的绘本
	 * 
	 * @param bookcase
	 * @return
	 */
	@PostMapping("/addSubscribe")
	public Msg addSubscribe(Bookcase bookcase, Integer sid) {
//		service.updateOverdue();
		List<Seriesandpicbook> findBySid = spService.findBySid(sid);
		List<Bookcase> list = new ArrayList<>();
		bookcase.setBType("2"); // 设置类型为 购买
		bookcase.setBTime(sdf.format(new Date()));
		for (Seriesandpicbook s : findBySid) {
			Bookcase b = new Bookcase();
			BeanUtils.copyProperties(bookcase, b);
			b.setBPicId(s.getSpPid());
			list.add(b);
		}
		boolean bool = service.batchInsert(list);
		return Msg.judge(bool);
	}

	/**
	 * 删除书架
	 * 
	 * @param ids
	 * @return
	 */
	@PostMapping("/batchDelete")
	public Msg batchDelete(int[] ids) {
		boolean bool = service.batchDelete(ids);
		return Msg.judge(bool);
	}

}
